from settings import conf


def _get_all_dictionary():
    from common.models.system import Dictionary
    # 排序后 is_value=False 的在前
    queryset = Dictionary.objects.filter(status=True).order_by('is_value')\
        .values('label', 'value', 'type', 'color', 'is_value', 'id', 'parent_id')
    result = []
    for index, instance in enumerate(queryset):
        if not instance['is_value']:
            instance['children'] = []
            continue
        elif not result:
            result = queryset[:index]
        # 遍历 is_value=False 的;
        for obj in result:
            if obj['id'] == instance['parent_id']:
                obj['children'].append(instance)
    return {ele.get('value'): ele for ele in result}


def refresh_dictionary():
    """刷新字典配置"""
    conf.DICTIONARY_CONFIG = _get_all_dictionary()


def get_dictionary_config():
    """获取字典所有配置"""

    if not conf.DICTIONARY_CONFIG:
        refresh_dictionary()
    return conf.DICTIONARY_CONFIG or dict()


def get_dictionary_values(key):
    """
    获取字典数据数组
    :param key: 对应字典配置的key值(字典编号)
    :return:
    """
    dictionary_config = get_dictionary_config()
    return dictionary_config.get(key, dict())


def get_dictionary_kv(key):
    dict_list = get_dictionary_values(key).get('children', [])
    result = dict()
    for i in dict_list:
        value = i.get('value')
        if i.get('type') == 6:
            value = True if value.lower() == 'true' else False
        result[value] = i.get('label')
    return result


def get_dictionary_label(key, name):
    """
    获取获取字典label值
    :param key: 字典管理中的key值(字典编号)
    :param name: 对应字典配置的value值
    :return:
    """
    children = get_dictionary_values(key) or []
    for ele in children:
        if ele.get('value') == str(name):
            return ele.get('label')
    return ''


# ================================================= #
# ******************** 初始化字典 ******************** #
# ================================================= #

def _get_all_system_config():
    data = {}
    from common.models.system import SystemConfig

    system_config_obj = (
        SystemConfig.objects.filter(parent_id__isnull=False)
        .values('parent__key', 'key', 'value', 'form_item_type')
        .order_by('sort')
    )
    for system_config in system_config_obj:
        value = system_config.get('value', '')
        if value and system_config.get('form_item_type') == 7:
            value = value[0].get('url')
        if value and system_config.get('form_item_type') == 11:
            new_value = []
            for ele in value:
                new_value.append({
                    'key': ele.get('key'),
                    'title': ele.get('title'),
                    'value': ele.get('value'),
                })
            new_value.sort(key=lambda s: s['key'])
            value = new_value
        data[f"{system_config.get('parent__key')}.{system_config.get('key')}"] = value
    return data


def refresh_system_config():
    """
    刷新系统配置
    :return:
    """
    conf.SYSTEM_CONFIG = _get_all_system_config()


def init_system_config():
    """
    初始化系统配置
    """
    try:
        conf.SYSTEM_CONFIG = _get_all_system_config()
    except Exception as e:
        print("请先进行数据库迁移!")
    return


def get_system_config():
    """
    获取系统配置中所有配置
    1.只传父级的key，返回全部子级，{ "父级key.子级key" : "值" }
    2."父级key.子级key"，返回子级值
    :return:
    """
    if not conf.SYSTEM_CONFIG:
        refresh_system_config()
    return conf.SYSTEM_CONFIG or {}


def get_system_config_values(key):
    """
    获取系统配置数据数组
    :param key: 对应系统配置的key值(字典编号)
    :return:
    """
    system_config = get_system_config()
    return system_config.get(key)


def get_system_config_label(key, name):
    """
    获取获取系统配置label值
    :param key: 系统配置中的key值(字典编号)
    :param name: 对应系统配置的value值
    :return:
    """
    children = get_system_config_values(key) or []
    for ele in children:
        if ele.get("value") == str(name):
            return ele.get("label")
    return ""
